package com.account.Interceptor;

import com.account.annotation.loginAnnotation;
import com.account.dao.AccountDao;
import com.account.entity.Account;
import com.alibaba.druid.util.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: lixiao
 * Created Date: 2020/4/7 21:59
 */
@Component(value = "loginVerification")
public class LoginVerification implements HandlerInterceptor {
    String token;
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod= (HandlerMethod) handler;

        boolean isAnnotationPresent = handlerMethod.getMethod().isAnnotationPresent(loginAnnotation.class);
        System.out.println(isAnnotationPresent);
        boolean hasMethodAnnotation = handlerMethod.hasMethodAnnotation(loginAnnotation.class);
        System.out.println(hasMethodAnnotation);
        token = request.getParameter("token");
        System.out.println("========================"+request.getRequestURI());
        if(StringUtils.isEmpty(token)){
            response.sendRedirect("/login/loginMsg");
            return false;
        }else{
            Account user = accountDao.findAccount(Integer.valueOf(token));
            if(user!=null){
                return true;
            }else{
                response.sendRedirect("/login/loginMsg");
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /**
         * controller处理之后
         */
        OutputStream output = response.getOutputStream();
        String data = "中国";
        output.write(data.getBytes("UTF-8"));
        output.flush();
        output.close();
        System.out.println("这是拦截器返回的数据");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("页面加载之后");
    }
}